package com.osi.project.common.intercaptor;

import com.osi.project.common.excaption.ProjectBusinessException;
import com.osi.start.common.business.dto.BaseDTO;
import com.osi.start.common.business.dto.RespVO;
import com.osi.start.common.business.service.ILocaleService;
import com.osi.start.common.util.SpringContextHolder;
import com.osi.start.framework.util.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 控制器异常处理
 * @Description
 * @Date 2019年2月18日
 */
@ControllerAdvice
@Slf4j
public class ControllerAdviceInterceptor {

    /**
     * 具体处理，确保错误已统一方式返回
     *
     * @param e
     * @return
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public RespVO<BaseDTO> exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        RespVO respVO = getYxRespVO(e);
        // 国际化处理
        String msg = convertMessage(respVO.getMsg());
        respVO.setMsg(msg);
        return respVO;
    }

    /**
     * 功能：国际化操作 异常后，切面 失效，此处可以有更好的方式 完善
     *
     * @param message
     * @return
     */
    private String convertMessage(String message) {
        ILocaleService localeService = SpringContextHolder.getBean("localeService");
        if (localeService == null) {
            return message;
        }
        return localeService.getMessage(message);
    }

    private RespVO getYxRespVO(Exception e) {
        if (e instanceof ProjectBusinessException) {
            ProjectBusinessException ex = (ProjectBusinessException) e;
            return new RespVO<>(ex.getCode(), ex.getMsg(), ex.getError());
        }
        return ExceptionUtil.getYxRespVO(e);
    }

}
